﻿using Share;
using System.Collections;
using UnityEngine;

/*
 * 背景音乐播放器，提供起始音乐和循环音乐播放
 */
public class AudioBGM : AudioBase
{
    private AudioSource m_AudioSource;
    private Coroutine m_PlayCoroutine;
    private string m_curPlayingName = "";

    public void Awake()
    {
        m_AudioSource = AudioManager.AddAudioSource(gameObject);
        m_AudioSource.pitch = 1;
    }
    public override void SetSpeed(float speed)
    {
        base.SetSpeed(speed);
        m_AudioSource.pitch = speed;
    }

    public override void SetVolume(float volume)
    {
        Volume = volume;
        m_AudioSource.volume = volume;
    }
    public void Play(string startName, float fadeTime = 0)
    {
        Play(startName, startName, fadeTime);
    }


    public void Play(string startName, string loopName, float fadeTime = 0)
    {
        // 如果当前播放的文件和需要播放的文件相同，直接返回
        if (m_curPlayingName == startName || m_curPlayingName == loopName)
        {
            return;
        }

        if (string.IsNullOrEmpty(startName) || string.IsNullOrEmpty(loopName))
        {
            Debug.LogError("Start or Loop audio name is invalid.");
            return;
        }

        if (m_AudioSource == null)
        {
            Debug.LogError("AudioSource is not initialized.");
            return;
        }

        // 停止之前的播放协程
        if (m_PlayCoroutine != null)
        {
            StopCoroutine(m_PlayCoroutine);
        }

        m_PlayCoroutine = StartCoroutine(DoPlayBGM(startName, loopName, fadeTime));
    }
    private IEnumerator DoPlayBGM(string startName, string loopName, float fadeInTime)
    {
        AudioClip startClip = ObjectMgr.Instance.CreateAudioClip(startName);
        if (startClip == null)
        {
            Debug.LogError($"Failed to load start audio: {startName}");
            yield break;
        }

        // 加载循环音频
        AudioClip loopClip = ObjectMgr.Instance.CreateAudioClip(loopName);
        if (loopClip == null)
        {
            Debug.LogWarning($"Failed to load loop audio: {loopName}, will use start audio instead");
            loopClip = startClip;
        }

        // 淡出当前音频
        if (m_AudioSource.isPlaying && fadeInTime > 0)
        {
            yield return StartCoroutine(FadeAudio(m_AudioSource, Volume, 0, fadeInTime));
        }

        // 播放起始音频
        m_AudioSource.clip = startClip;
        m_AudioSource.loop = false;
        m_AudioSource.volume = Volume;
        m_AudioSource.Play();
        m_curPlayingName = startName;

        // 淡入起始音频
        if (fadeInTime > 0)
        {
            yield return StartCoroutine(FadeAudio(m_AudioSource, 0, Volume, fadeInTime));
        }

        // 等待起始音频播放完成
        yield return new WaitForSecondsRealtime(startClip.length);

        // 播放循环音频
        m_AudioSource.clip = loopClip;
        m_AudioSource.loop = true;
        m_AudioSource.volume = Volume;
        m_AudioSource.Play();

        // 淡入循环音频
        if (fadeInTime > 0)
        {
            yield return StartCoroutine(FadeAudio(m_AudioSource, 0, Volume, fadeInTime));
        }

        m_curPlayingName = loopClip == startClip ? startName : loopName;
    }

    private IEnumerator FadeAudio(AudioSource audioSource, float from, float to, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            audioSource.volume = Mathf.Lerp(from, to, elapsed / duration);
            elapsed += Time.deltaTime;
            yield return null;
        }
        audioSource.volume = to;
    }

    public override void Stop()
    {
        if (m_PlayCoroutine != null)
        {
            StopCoroutine(m_PlayCoroutine);
            m_PlayCoroutine = null;
        }

        if (m_AudioSource != null && m_AudioSource.isPlaying)
        {
            m_AudioSource.Stop();
        }
        m_curPlayingName = "";
    }


}
